﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WarOfDev.EF;
using WarOfDev.Web.ViewModels;
using WarOfDev.Web.ViewModels.MappingToModel;
using WarOfDev.Web.Models.MappingToViewModel;
using WarOfDev.Core.ActionFilters;
using WarOfDev.Core.ExceptionHandling.Attributes;

namespace WarOfDev.Web.Controllers
{
    public class UserController : BaseController
    {
        private WarDevEntities db = new WarDevEntities();
        //
        // GET: /User/
        [CustomAuthorize("UserAdmin.ShowUsers")]
        [ViewHandleError(IsPartial = false)]
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(string id = null)
        {
            WarOfDev.EF.User user = db.Users.Single(u => u.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            ViewBag.GroupId = new SelectList(db.Groups, "Id", "GroupName");
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(UserViewModel user)
        {
            if (ModelState.IsValid)
            {
                user.Id = Guid.NewGuid().ToString();
                user.UserId = string.Empty;

                user.Roles = Request["roles"].ToString();


                db.Users.AddObject(user.ToModel());
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(user);
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(string id = null)
        {
            WarOfDev.EF.User user = db.Users.Include("Roles").SingleOrDefault(u => u.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user.ToViewModel());
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(UserViewModel user)
        {
            if (ModelState.IsValid)
            {
                var tempUser = new WarOfDev.EF.User { Id = user.Id };

                db.Users.Attach(tempUser);
                tempUser.UserName = user.UserName;
                tempUser.Password = user.Password;
                tempUser.IsLocked = user.IsLocked;
                tempUser.Description = user.Description;
                tempUser.ModifiedOn = DateTime.Now;
                tempUser.ModifiedBy = this.CurrentUser.Id;

                var roles = Request["roles"].ToString();

                db.UserRoles.Where(ur => ur.UserId == user.Id).ToList().ForEach(r => db.UserRoles.DeleteObject(r));
                db.UserGroups.Where(ug => ug.UserId == user.Id).ToList().ForEach(g => db.UserGroups.DeleteObject(g));
                var userRoles = roles.Split(',').Select(r => new  WarOfDev.EF.UserRole
                {
                    Id = Guid.NewGuid().ToString(),
                    UserId = user.Id,
                    RoleId = r,
                    CreatedBy = this.CurrentUser.Id,
                    ModifiedBy = this.CurrentUser.Id,
                    CreatedOn = DateTime.Now,
                    ModifiedOn = DateTime.Now
                });

                foreach (var r in userRoles)
                {
                    tempUser.Roles.Add(r);
                }

                tempUser.Groups.Add(new  WarOfDev.EF.UserGroup { Id = Guid.NewGuid().ToString(), GroupId = user.GroupId, UserId = user.Id, ModifiedOn = DateTime.Now });

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(string id = null)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            WarOfDev.EF.User user = db.Users.Single(u => u.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }

            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            WarOfDev.EF.User user = db.Users.Single(u => u.Id == id);
            var userGroups = db.UserGroups.Where(ug => ug.UserId == id).ToList();
            var userRoles = db.UserRoles.Where(ur => ur.UserId == id).ToList();

            foreach (var item in userGroups)
            {
                db.UserGroups.Attach(item);
                db.ObjectStateManager.ChangeObjectState(item, EntityState.Deleted);
            }

            foreach (var item in userRoles)
            {
                db.UserRoles.Attach(item);
                db.ObjectStateManager.ChangeObjectState(item, EntityState.Deleted);
            }

            db.Users.DeleteObject(user);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult GetAllRoles(string roles, string groupId)
        {
            IEnumerable<SelectListItem> roleList = new List<SelectListItem>();
            var tempRoles = roles.Split(',');

            if (string.IsNullOrEmpty(roles))
            {
                if (string.IsNullOrEmpty(groupId))
                {
                    roleList = db.Roles.AsEnumerable().Select(r => new SelectListItem { Text = r.RoleName, Value = r.Id }).ToList();
                }
                else
                {
                    roleList = db.Roles.Where(r => r.Groups.FirstOrDefault(g => g.GroupId == groupId) != null).AsEnumerable().Select(r => new SelectListItem { Text = r.RoleName, Value = r.Id }).ToList();
                }
            }
            else
            {
                if (string.IsNullOrEmpty(groupId))
                {
                    roleList = db.Roles.AsEnumerable().Select(r => new SelectListItem { Text = r.RoleName, Value = r.Id, Selected = tempRoles.Contains(r.Id) }).ToList();
                }
                else
                {
                    roleList = db.Roles.Where(r => r.Groups.FirstOrDefault(g => g.GroupId == groupId) != null).AsEnumerable().Select(r => new SelectListItem { Text = r.RoleName, Value = r.Id, Selected = tempRoles.Contains(r.Id) }).ToList();
                }
            }

            return PartialView("_AllRoles", roleList);
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}